package com.easy.work.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.base.syslib.Logs;
import com.base.syslib.pulltorefresh.PullToRefreshBase;
import com.base.syslib.pulltorefresh.PullToRefreshGridView;
import com.base.syslib.util.DateTimeHelper;
import com.base.syslib.util.MessageTools;
import com.base.syslib.view.HeaderGridView;
import com.base.syslib.view.viewpager.CarouseFigureBean;
import com.base.syslib.view.viewpager.CycleViewPager;
import com.easy.work.MainActivity;
import com.easy.work.R;
import com.easy.work.app.AppSession;
import com.easy.work.app.BaseFragment;
import com.easy.work.bean.MallGoodsBean;
import com.easy.work.function.WebViewAct;
import com.easy.work.function.mall.CommodityDetailAct;
import com.easy.work.function.mall.MallListAdapter;
import com.easy.work.function.mall.activity.ExchangeRecordActivity;
import com.easy.work.http.BaseResponse;
import com.easy.work.http.HttpClient;
import com.easy.work.http.request.CarouseFigureRequest;
import com.easy.work.http.request.MallGoodsListInfoRequest;
import com.easy.work.http.request.SignRequest;
import com.easy.work.http.response.CarouseFigureList;
import com.easy.work.http.response.MallGoodsList;
import com.easy.work.http.response.ResumeInfoResponse;
import com.easy.work.utils.SP.SPKey;
import com.easy.work.utils.ViewFactory;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Admin on 2017/12/6.
 * 商城
 */
public class MallFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListener<HeaderGridView> {

    HeaderGridView gridView;
    @BindView(R.id.refreshGridView)
    PullToRefreshGridView refreshGridView;
    Unbinder unbinder;
    ImageView img_qiandao;
    private CycleViewPager cycleViewPager;
    private MallListAdapter adapter;

    /**
     * 推荐好友领积分
     */
    private TextView tv_tuijianhaoyou;
    /**
     * 积分
     */
    private int integral;

    //listview的顶部head
    View headerView;
    /**
     * 广告页面数据
     */
    public List<CarouseFigureBean> ADInfoList = new ArrayList<>();

    /**
     * 兑换商品列表
     */
    public List<MallGoodsBean> mallGoodsList = new ArrayList<>();


    TextView tv_jinbi_num;
//    /**
//     * 加载位置坐标
//     */
//    private int currentPage = 0;

    @Override
    public int getFragmentLayout() {
        return R.layout.refresh_grid_view;
    }


    void initView(View view) {
        adapter = new MallListAdapter(getContext(), mallGoodsList);
        refreshGridView.setPullLoadEnabled(true);
        refreshGridView.setPullRefreshEnabled(true);
        refreshGridView.setOnRefreshListener(this);
        gridView = refreshGridView.getRefreshableView();

        gridView.setNumColumns(2);
        headerView = View.inflate(getActivity(), R.layout.frag_mall, null);
        cycleViewPager = (CycleViewPager) getActivity().getFragmentManager()
                .findFragmentById(R.id.main_viewPager1);
        findHeadView(headerView);
        gridView.addHeaderView(headerView);
//        EmptyAdapter emptyAdapter = new EmptyAdapter(getContext());
        gridView.setAdapter(adapter);
        AppSession.setPullFormartRefreshTime(refreshGridView);
        refreshGridView.doPullRefreshing(true, 0);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MallGoodsBean bean = (MallGoodsBean) parent.getAdapter().getItem(position);
                CommodityDetailAct.start(getContext(), bean);
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        initView(rootView);

        refreshGridView.doPullRefreshing(true, 0);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            //隐藏时所作的事情

        } else {
            //显示时所作的事情
            ResumeInfoResponse resumeInfoResponse = ((MainActivity) getActivity()).resumeInfoResponse;
            if (resumeInfoResponse == null) {
                return;
            }
            integral = resumeInfoResponse.integral;
            tv_jinbi_num.setText(integral + "");
        }
    }

    /**
     * 头部布局初始化
     *
     * @param view
     */
    private void findHeadView(View view) {
        tv_tuijianhaoyou = (TextView) view.findViewById(R.id.tv_tuijianhaoyou);
        tv_jinbi_num = (TextView) view.findViewById(R.id.tv_jinbi_num);
        RelativeLayout rl_duihuanjilv = (RelativeLayout) view.findViewById(R.id.rl_duihuanjilv);
        img_qiandao = (ImageView) view.findViewById(R.id.img_qiandao);
        showQiandaoView();
        rl_duihuanjilv.setOnClickListener(iconListener);
        img_qiandao.setOnClickListener(iconListener);
        tv_tuijianhaoyou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WebViewAct.start(getContext(), "http://v.xiumi.us/board/v5/38S4p/79649644", "推荐好友注册领更多积分链接");
            }
        });

    }

    private void sign() {
        SignRequest signRequest = new SignRequest();
        signRequest.userId = AppSession.getInstance().getUserId();
        HttpClient.post(signRequest, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                MessageTools.showToast(getContext(), "签到成功");
                integral += 10;
                tv_jinbi_num.setText(integral + "");
                AppSession.getInstance().saveAppSessionData(SPKey.Qiandao_Time, DateTimeHelper.getCurrentDay());
                img_qiandao.setBackground(getResources().getDrawable(R.mipmap.qiandaolingjifen_un));
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                MessageTools.showToast(getContext(), msg);
                AppSession.getInstance().saveAppSessionData(SPKey.Qiandao_Time, DateTimeHelper.getCurrentDay());
                img_qiandao.setBackground(getResources().getDrawable(R.mipmap.qiandaolingjifen_un));
            }
        });
    }

    private View.OnClickListener iconListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.rl_duihuanjilv:
                    ExchangeRecordActivity.goExchangeRecordActivity(getActivity());
                    break;
                case R.id.img_qiandao:
                    //签到
                    sign();
                    break;
            }
        }
    };

    /**
     * 展示签到
     */
    private void showQiandaoView() {
        String day = DateTimeHelper.getCurrentDay();
        String qiandaoDay = AppSession.getAppSPData(SPKey.Qiandao_Time);
        if (day.equals(qiandaoDay)) {
            img_qiandao.setBackground(getResources().getDrawable(R.mipmap.qiandaolingjifen_un));
        } else {
            img_qiandao.setBackground(getResources().getDrawable(R.mipmap.qiandaolingjifen));

        }


    }

    /**
     * 获取轮播广告业信息
     */
    private void getAD() {
        final CarouseFigureRequest request = new CarouseFigureRequest();
        request.type = "2";
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                Logs.e("mallfragment", response.toString());
                CarouseFigureList carouseFigureList = (CarouseFigureList) response;
                ADInfoList = carouseFigureList.list;
//                    ADInfoList = carouseFigureEntity.body;
                initialize(ADInfoList);
                refreshGridView.onPullUpRefreshComplete();
                refreshGridView.onPullDownRefreshComplete();
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
            }
        });

    }


    /**
     * 获取兑换商品信息列表
     */
    private void getMallGoodsListInfo() {
        final MallGoodsListInfoRequest request = new MallGoodsListInfoRequest();
        request.start = adapter.getCount();
        request.limit = "10";
        Logs.e("mallFragment", "currentPage = " + request.start);
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {

                Logs.e("mallFragment", "response = " + response);
                MallGoodsList baseList = (MallGoodsList) response;
                if (baseList != null && baseList.list != null && baseList.list.size() > 0) {

                    List<MallGoodsBean> addList = baseList.list;
                    mallGoodsList.addAll(addList);

                    int size = baseList.list.size();
                    if (size < 10) {
                        refreshGridView.setHasMoreData(false);
                    }

                    Logs.e("mallFragment", "baseList.list.size() = " + size);
                }

//                gridView.setAdapter(adapter);
//                if (currentPage != 0) {
//                    gridView.scrollListBy(size);
//                }
                adapter.notifyDataSetChanged();
                refreshGridView.onPullDownRefreshComplete();
                refreshGridView.onPullUpRefreshComplete();
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                Logs.d("MainFragment", "WorkBaseListInfoRequest    code" + code + "      msg=" + msg);
            }
        });

    }


    /**
     * 加载轮播图
     *
     * @param infos
     */
    @SuppressLint("NewApi")
    private void initialize(List<CarouseFigureBean> infos) {
        if (infos == null || infos.size() < 1) {
            return;
        }

        List<ImageView> views = new ArrayList<ImageView>();
        // 将最后一个ImageView添加进来
        views.add(ViewFactory.getImageView(getContext(), infos.get(infos.size() - 1).imgAddress));
        for (int i = 0; i < infos.size(); i++) {
            views.add(ViewFactory.getImageView(getContext(), infos.get(i).imgAddress));
        }
        // 将第一个ImageView添加进来
        views.add(ViewFactory.getImageView(getContext(), infos.get(0).imgAddress));

        // 设置循环，在调用setData方法前调用
        cycleViewPager.setCycle(true);

        // 在加载数据前设置是否循环
        cycleViewPager.setData(views, infos, mAdCycleViewListener);
        //设置轮播
        cycleViewPager.setWheel(true);

        // 设置轮播时间，默认5000ms
        cycleViewPager.setTime(2000);
        //设置圆点指示图标组居中显示，默认靠右
        cycleViewPager.setIndicatorCenter();
    }

    private CycleViewPager.ImageCycleViewListener mAdCycleViewListener = new CycleViewPager.ImageCycleViewListener() {

        @Override
        public void onImageClick(CarouseFigureBean info, int position, View imageView) {
            if (cycleViewPager.isCycle()) {
                position = position - 1;
                CarouseFigureBean bean = ADInfoList.get(position);
                WebViewAct.start(getContext(), bean.eventUrl, "易上班");
            }
        }

    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase<HeaderGridView> refreshView) {
        mallGoodsList.clear();
        getAD();
        getMallGoodsListInfo();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<HeaderGridView> refreshView) {
        if (mallGoodsList.size() < 9) {
            return;
        }
        getMallGoodsListInfo();
    }
}
